package com.ukefu.webim.service.es;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;

import com.ukefu.core.UKDataContext;
import com.ukefu.webim.web.model.OnlineUser;

public class OnlineSimpleRepositoryImpl implements OnlineSimpleCommonRepository{
	private ElasticsearchTemplate elasticsearchTemplate;

	
	@Autowired
	public void setElasticsearchTemplate(ElasticsearchTemplate elasticsearchTemplate) {
        this.elasticsearchTemplate = elasticsearchTemplate ;
    }

	@Override
	public Page<OnlineUser> findAll(Pageable page) {
		Page<OnlineUser> pages  = null ;
		BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
		boolQueryBuilder.must(QueryBuilders.termQuery("status" , UKDataContext.OnlineUserOperatorStatus.ONLINE.toString())) ;
	    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("updatetime").unmappedType("date").order(SortOrder.ASC));
	    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(page) ;
	    if(elasticsearchTemplate.indexExists(OnlineUser.class)){
	    	pages = elasticsearchTemplate.queryForPage(searchQuery, OnlineUser.class);
	    }
	    return pages ; 
	}
}
